#pragma once

#include <iostream>
#include <string>
#include "LockGuard.hpp"
#include "Log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include "InetAddr.hpp"
#include <unistd.h>
#include <sys/wait.h>
#include <functional>
#include <pthread.h>

#include "Socket.hpp" //以后创建，绑定套接字什么的都在这里面了，包头文件用即可
#include <memory>

using namespace socket_ns; // 展开命名空间

class TcpServer; // 前置声明

using io_service_t = std::function<void (socket_sptr sockfd, InetAddr client)>;

class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, io_service_t service)
        : _localaddr("0", port), _listensockfd(std::make_unique<TcpSocket>()), _isrunning(false), _service(service)
    {
        _listensockfd->BuildListenSocket(_localaddr); // 构造服务器，一步就创建套接字bind，listen什么全做好了封装的效果
    }
    static void *HandlerSock(void *args)
    {
        // 线程分离，不用主线程回收
        pthread_detach(pthread_self()); // pthread_self()获取当前线程自己的UID
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        ::close(td->sockfd->SockFd()); // 文件描述符泄漏
        delete td;                     // 每个客户端退出后，线程资源释放掉
        return nullptr;
    }
    // 启动
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 4. 不能直接接受数据，先获取连接
            InetAddr peeraddr;
            socket_sptr normalsock = _listensockfd->Accepter(&peeraddr);
            // 连接成功的话，就分配一个新的sockfd
            if (normalsock == nullptr)
                continue;
            // version 2: 采用多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this); // 每个线程客户端都要配一份，堆开辟
            pthread_create(&tid, nullptr, HandlerSock, td);              // 线程分离，不用管回收
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensockfd;
    bool _isrunning;
    io_service_t _service;
};
